package com.sx.pipeline.ui.chat.group

import android.net.Uri
import android.view.View
import androidx.annotation.NonNull
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.sx.mvvmlibs.utils.Logs
import com.sx.pipeline.BR
import com.sx.pipeline.R
import com.sx.pipeline.adapter.RongGroupListAdapter
import com.sx.pipeline.app.base.CYDataBindingBaseActivity
import com.sx.pipeline.arouth.RouteManager
import com.sx.pipeline.arouth.RoutePath
import com.sx.pipeline.databinding.ActGroupChatBinding
import com.sx.pipeline.repos.http.res.RongGroupVO
import com.sx.pipeline.ui.chat.ChatVM
import io.rong.imkit.RongIM
import io.rong.imkit.utils.RouteUtils
import io.rong.imlib.model.Conversation


/**
 * @Author: YY
 * @Date: 2022/4/5
 * @Description: 群聊
 */
@Route(path = RoutePath.Chat.CHAT_GROUP)
class GroupChatActivity : CYDataBindingBaseActivity<ActGroupChatBinding, ChatVM>(
    R.layout.act_group_chat), View.OnClickListener {
    private lateinit var mAdapter: RongGroupListAdapter


    override fun initData() {
        mBinding.setVariable(BR.onClick, this)
        mBinding.titleBar.leftView.setOnClickListener {
            finish()
        }

        // 获取群组列表
        mViewModel.getRongGroupList()
    }


    override fun initListener() {
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {

            override fun onLoadMore(@NonNull refreshLayout: RefreshLayout) {
               mBinding.refreshLayout.finishLoadMoreWithNoMoreData()
            }

            override fun onRefresh(@NonNull refreshLayout: RefreshLayout) {
                mPage = 1
                mViewModel.getRongGroupList()
                mBinding.refreshLayout.finishRefresh()
            }
        })
    }

    override fun onClick(v: View?) {
        when (v?.id) {

        }
    }

    override fun onResume() {
        super.onResume()
        mPage = 1
        mViewModel.getRongGroupList()
    }

    override fun initViewObservable() {
        super.initViewObservable()

        // 刷新事件
        observe(mViewModel.mUI.initRefreshEvent()) {
            mBinding.refreshLayout.finishRefresh(it!!)
        }

        // 加载事件
        observe(mViewModel.mUI.initLoadEvent()) {
            mBinding.refreshLayout.finishLoadMore(it!!)
        }

        // 群组列表
        setGroupList()

    }

    private fun setGroupList() {
        // 群组列表
        observe(mViewModel.groupListEvent) {
            if (it != null && !it.isNullOrEmpty()) {
                refreshRongGroupInfo(it)
                mBinding.emptyView.visibility = View.GONE
                if (!this::mAdapter.isInitialized) {
                    mBinding.recyclerView.layoutManager = LinearLayoutManager(
                        this, LinearLayoutManager.VERTICAL, false)
                    mAdapter = RongGroupListAdapter(it as MutableList<RongGroupVO>)
                    mBinding.recyclerView.adapter = mAdapter
                    mAdapter.setOnItemClickListener { adapter, view, position ->
                        val info = adapter.data[position] as RongGroupVO
//                        RouteUtils.routeToConversationActivity(this, Conversation.ConversationType.GROUP, info.id)
                        ARouter.getInstance().build(RoutePath.Chat.CHAT_DETAIL)
                            .withString("targetId",info.id)
                            .withString("ConversationType",
                                Conversation.ConversationType.GROUP.toString()
                            )
                            .navigation()
                    }
                } else {
                    mBinding.refreshLayout.setEnableLoadMore(true)
                    if (mPage == 1) {
                        mAdapter.setNewInstance(it as MutableList<RongGroupVO>)
                    } else {
                        mAdapter.addData(it)
                    }
                }
//                if (mAdapter.data.size == it.total) {
//                    mBinding.refreshLayout.setEnableLoadMore(false)
//                }
            } else {
                mBinding.refreshLayout.setEnableLoadMore(false)
                mBinding.emptyView.visibility = View.VISIBLE
                mBinding.recyclerView.visibility=View.GONE
            }
        }
    }

    private fun refreshRongGroupInfo(friendList: List<RongGroupVO>) {
        //融云IM -> 刷新群组信息
        for (i in friendList.indices) {
            //后台拿到的联系人列表id 比对 融云id相同则缓存
            val group = io.rong.imlib.model.Group(
                friendList[i].id,
                friendList[i].name,
                Uri.parse("")
            )
            //通过网络请求动态加载群信息
            RongIM.getInstance().refreshGroupInfoCache(group)
            Logs.d("re缓存群聊信息成功：" + group)
        }
    }
}